#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-10-7'
# code is far away from bugs with the god animal protecting ~
"""
import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from users.models import User
from users.utils import generate_jwt_token


class CreateUserSerializer(serializers.ModelSerializer):
	password2 = serializers.CharField(label='确认密码', write_only=True)
	sms_code = serializers.CharField(label='短信验证码', write_only=True)
	allow = serializers.BooleanField(label='同意用户协议', write_only=True)
	token = serializers.CharField(label='用户登陆令牌', read_only=True)

	# def create(self, validated_data):
	# 	return User.objects.create_user(username=validated_data.get('username'),
	# 		password=validated_data.get('password'), mobile=validated_data.get('mobile'), )

	def create(self, validated_data):
		"""创建用户"""

		# 移除数据库模型类中不存在的属性
		del validated_data['password2']
		del validated_data['sms_code']
		del validated_data['allow']
		user = super().create(validated_data)

		# 调用django的认证系统加密密码
		user.set_password(validated_data['password'])
		user.save()

		# 补充生成记录登录状态的token
		user.token = generate_jwt_token(user)
		return user


	def validate_moblie(self, value):
		'''验证手机号码'''
		if not re.match(r'^1[3-9]\d{9}$', value):
			raise serializers.ValidationError('手机号码格式错误')
		return value

	def validate_allow(self, value):
		if not value:
			raise serializers.ValidationError('请同意用户协议')
		return value

	def validate(self, attrs):
		# 判断两次密码
		if attrs['password'] != attrs['password2']:
			raise serializers.ValidationError('两次密码不一致')

		# 判断短信验证码
		redis_conn = get_redis_connection('verify_code')
		mobile = attrs['mobile']
		real_sms_code = redis_conn.get('sms_%s' % mobile)
		if real_sms_code is None:
			raise serializers.ValidationError('无效的短信验证码')

		if attrs['sms_code'] != real_sms_code.decode():
			raise serializers.ValidationError('短信验证码错误')

		return attrs

	class Meta:
		model = User
		fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')

		extar_kwargs = {
			'username' : {
				'min_length' : 5,
				'max_length' : 20,
				'error_messages' : {'min_length': '用户名需大于5个字符', 'max_length': '用户名需小于20个字符'}
				},
			'password' : {
				'write_only': True,
				'min_length': 5,
				'max_length': 20,
				'error_messages': {'min_length': '密码需大于5个字符', 'max_length': '密码需小于20个字符'}
				}
		}


if __name__ == '__main__':
	pass
